using gpcx.Properties;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace gpcx
{
    public sealed class NotificationIcon
	{
		private readonly NotifyIcon _notifyIcon;

		//private readonly ContextMenu _notificationMenu;

		private Thread _th1;

		private bool _bool1 = true;
		private TopFrm topfrm;
		private SettingFrm settingfrm;
		private MenuFrm menuFrm;
		private List<ValueTuple<string, string, string, string, string, string, string>> StockDatas;

		private NotificationIcon()
		{
			_notifyIcon = new NotifyIcon();
			//_notificationMenu = new ContextMenu(InitializeMenu());
			_notifyIcon.DoubleClick += IconDoubleClick;
			//new ComponentResourceManager(typeof(NotificationIcon));
			_notifyIcon.Icon = Resources.menuico;
			//_notifyIcon.ContextMenu = _notificationMenu;
			topfrm = new TopFrm
			{
				AppExit = new Action(() =>
				{
					_th1.Abort();
					_th1.Join();
					Application.Exit();
				})
			};
			topfrm.Hide();
			menuFrm = new MenuFrm
			{
				ShowTopFrm = new Action(() =>
				{
					topfrm.Show();
					topfrm.UpdateData(StockDatas.Where(o => !string.IsNullOrEmpty(o.Item6)).ToList());
					topfrm.RefreshData = new Action(() =>
					{
						_bool1 = false;
						refdata();
					});
				}),
				ShowSettingFrm = new Action(() =>
				{
					if (settingfrm == null || settingfrm.Visible == false)
						settingfrm = new SettingFrm(StockDatas.Select(o => new ValueTuple<string, string>(o.Item7, o.Item1)).ToList());
					settingfrm.Show();
				}),
				Refdata = new Action(() =>
				{
					_bool1 = false;
					refdata();
				}),
				AppExit = new Action(() =>
				{
					_th1.Abort();
					_th1.Join();
					Application.Exit();
				})
			};
			menuFrm.Hide();
			StockDatas = new List<(string, string, string, string, string, string, string)>();
			_th1 = new Thread(Run);
			_th1.Start();
			_notifyIcon.MouseClick += _notifyIcon_MouseClick;
		}

        private void _notifyIcon_MouseClick(object sender, MouseEventArgs e)
        {
            if(e.Button == MouseButtons.Right)
            {
				menuFrm.Show();
				menuFrm.TopMost = true;
				menuFrm.UpdateData(StockDatas);
				menuFrm.Location = new System.Drawing.Point(Control.MousePosition.X - menuFrm.Width, Control.MousePosition.Y - menuFrm.Height);
			}
        }

		[STAThread]
		public static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			bool flag;
			using (new Mutex(true, "gpcx", out flag))
			{
			    if (!flag) return;
			    var notificationIcon = new NotificationIcon {_notifyIcon = {Visible = true}};
			    Application.Run();
			    notificationIcon._notifyIcon.Dispose();
			}
		}

		private void IconDoubleClick(object sender, EventArgs e)
		{
		    if (_bool1) return;

		    _bool1 = true;
		    ThreadStart start = Run;
		    _th1 = new Thread(start);
		    _th1.Start();
		}

		private void Run()
		{
            try
            {
				do
				{
					var refTime = 10000;

					try
                    {
						refTime = int.Parse(ConfigManager.GetAppSettingsKeyValue("refTime") ?? "10") * 1000;
					}
                    catch
                    {
						refTime = 10000;
						ConfigManager.UpdateSetting("refTime","10");
					}
					refdata();
					Thread.Sleep(refTime);
				}
				while (_th1 != null && _bool1);
			}
		    catch (Exception)
            {
		        // ignored
		    }
		}

		private void refdata()
		{
			var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://qt.gtimg.cn/q=" + ConfigManager.GetAppSettingsKeyValue("gpdm"));
			var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
			var streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.Default);
			var text = streamReader.ReadToEnd();
			streamReader.Close();
			var array = text.Split(';');
			var num = 1;
			var array2 = array;
			StockDatas.Clear();
			foreach (var text2 in array2)
			{
				var data = new ValueTuple<string,string,string,string,string,string,string>();
			    var array3 = text2.Split('~');
			    if (array3.Length > 5)
				{
					data.Item1 = array3[1];
					data.Item2 = array3[2];
					if (!array3[0].Contains("s_sh000") && !array3[0].Contains("s_sz399"))
					{
						data.Item3 = array3[3];
						data.Item4 = array3[4];
						data.Item5 = array3[5];
						data.Item6 = $"{array3[6]}手\r\n{array3[7]}万";
					}
                    else
					{
						data.Item3 = array3[3];
						data.Item5 = array3[5];
					}
					data.Item7 = array3[0].Split('=')[0].Split(new []{ '_'},2)[1];
					StockDatas.Add(data);
				}
			    num++;
			}

			if(menuFrm.Visible)
				menuFrm.UpdateData(StockDatas);
			if (topfrm.Visible)
				topfrm.UpdateData(StockDatas.Where(o=> !string.IsNullOrEmpty(o.Item6)).ToList());
		}
	}
}
